package wnxy.wn44.shopwn.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import wnxy.wn44.shopwn.entity.Perm;
import wnxy.wn44.shopwn.service.UserService;
import wnxy.wn44.shopwn.utils.CookieUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@Order(2)
public class SecondInterceptor implements HandlerInterceptor {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("拦截器2收到请求:\t" + request.getRequestURI());

        //-- 用户是否可以访问到资源，由这个拦截器决定，该拦截器怎么知道用户是否由权限访问资源呢？

        //-- 获取用户的权限列表，遍历权限列表中资源的地址和请求的地址是否匹配
        Cookie cookie = CookieUtils.getCookie("userId", request.getCookies());

        System.out.println("拦截器2:cookie" + cookie);

        //-- 获取登录用户的权限列表
        List<Perm> permissionList = userService.findByJointQuery(Integer.parseInt(cookie.getValue()));//--getValue对应的就是UserId

        System.out.println("permisssionList:\t" + permissionList);

        //-- 获取请求的资源地址
        String requestURI = request.getRequestURI();
        System.out.println("requestUri" + requestURI);

        //-- 提供一个标识 用于标识是否由权限
        boolean isHave = false;

        if (permissionList != null) {
            //-- 遍历从数据库得到的权限列表
            for (Perm permission : permissionList) {

                //-- 判断是否有权限
                if (permission.getName().equals(requestURI)) {
                    isHave = true;
                    break;
                }
            }

            if (isHave) {
                return true;
            }
        }


        //-- true 放行  false 拦截
        response.sendRedirect("/noPerm.html");
        return false;

    }
}
